package org.wei.tbk;

import java.util.HashMap;

import com.google.appengine.repackaged.org.apache.commons.logging.Log;
import com.google.appengine.repackaged.org.apache.commons.logging.LogFactory;
import com.google.appengine.repackaged.org.json.JSONArray;
import com.google.appengine.repackaged.org.json.JSONObject;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.SellercatsListGetRequest;
import com.taobao.api.response.SellercatsListGetResponse;

public class APIInvoke {
	public static Log log = LogFactory.getLog(APIInvoke.class);
	
	public static HashMap<String,String> invoke(String shopId) {

//		// 设置代理上外网
//		System.getProperties().put("proxySet", "true");
//		// System.getProperties().put("proxyHost", "10.6.13.23");
//		System.getProperties().put("proxyHost", "proxy.tencent.com");
//		System.getProperties().put("proxyPort", "8080");
		TaobaoClient client = new DefaultTaobaoClient(
				"http://gw.api.tbsandbox.com/router/rest", "test", "test");
		try {
			SellercatsListGetRequest req = new SellercatsListGetRequest();
			req.setNick(shopId);
			req.setFields("cid,name");
			SellercatsListGetResponse response = client.execute(req);
			if(response.isSuccess()) {
				return converResponse2Map(response);
			}else{
				return null;
			}
		} catch (ApiException e) {
			log.error("调用taobao API异常", e);
			return null;
		}
	}
	
	/**
	 * 把返回的json数据，解析成cid：name的map
	 * @param response
	 * @return
	 */
	private static HashMap<String,String> converResponse2Map(SellercatsListGetResponse response){
		 HashMap<String,String> map = new  HashMap<String,String>();
		try {
			JSONObject jo = new JSONObject(response.getBody());
			JSONArray arrays = jo.getJSONObject("sellercats_list_get_response")
					.getJSONObject("seller_cats").getJSONArray("seller_cat");
			if(arrays!=null &&arrays.length()>0) {
				for(int i=0; i<arrays.length();i++) {
					JSONObject obj = (JSONObject)arrays.get(i);
					map.put(obj.getString("cid"), obj.getString("name"));
				}
			}
			return map;
		} catch (Exception e) {
			return null;
		}
	}

	//测试involve， response
//	public static void main(String[] args) {
//		//SellercatsListGetResponse invoke = invoke("alipublic01");
//		try {
//			//System.out.println(invoke.getBody());
//			//获取自定义分类的cid/name Array
//			JSONObject jo = new JSONObject(invoke.getBody());
//			JSONArray arrays = jo.getJSONObject("sellercats_list_get_response")
//					.getJSONObject("seller_cats")
//					.getJSONArray("seller_cat");
//			
//			System.out.println( ((JSONObject)arrays.get(0)).getString("cid") +"  "+ ((JSONObject)arrays.get(0)).getString("name"));
//		} catch (JSONException e) {
//			e.printStackTrace();
//		}
//	}
}
